import os
import random
import shutil
import sys
import math
import time
import subprocess

cmd_head = 'java -Xms256M -Xmx1000M -classpath bin ml.MLSimulator'
data = './data/H1/EURUSD60_SAMPLES.csv'
label = './data/H1/EURUSD60_LABELS.csv'
start = '0'
use_num = '-1'
asset = './data/H1/EURUSD60_ASSETS.csv'
rise_classifier = './data/H1/EURUSD60_rise_classifier.dat'
drop_classifier = './data/H1/EURUSD60_drop_classifier.dat'
valued_classfier_dir_root = './data/H1/valued_classifier/EURUSD'

data_num = 0
with open(data) as h_data:
    for line in h_data:
        data_num += 1
        
min_use_num = 2000
max_use_num = 8000
min_profit_factor = 2.17
min_max_profit_rate = 2
period = 2	# TODO: change this to 10 to view the consecution of the profit
i = 0
selected = 0
while True:
    try:
        i += 1
        print 'cycle:', i, '\tselected:', selected
        if os.path.isfile(rise_classifier):
            os.unlink(rise_classifier)
        if os.path.isfile(drop_classifier):
            os.unlink(drop_classifier)
        start = str(random.randint(0, data_num-min_use_num))
        use_num = str(random.randint(min_use_num, max_use_num))
        cmd = ' '.join([cmd_head, data, label, start, use_num, asset, rise_classifier, drop_classifier])
        p=subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
        p.wait()
        
        with open(asset) as h_asset:
            line_str = (h_asset.readline()).split()
            step = int(len(line_str)/period)
            profit_rates = []
            init_asset = eval(line_str[0])
            for index in xrange(0, len(line_str), step):
                profit_rates.append((eval(line_str[min(len(line_str)-1, index+step-1)])-eval(line_str[index]))/init_asset)
            profit_rates.sort()

            profit_factor = sum(profit_rates)/len(profit_rates)
            if (profit_factor > min_profit_factor):
                if min_profit_factor*min_max_profit_rate < profit_factor:
                     min_profit_factor = profit_factor/min_max_profit_rate
                dir_name = os.path.join(valued_classfier_dir_root, ('_'.join([str(profit_factor), str(i), start, use_num])))
                os.makedirs(dir_name)
                shutil.move(rise_classifier, dir_name)
                shutil.move(drop_classifier, dir_name)
                shutil.move(asset, dir_name)
                selected += 1
    except KeyboardInterrupt:
        print 'final cycle:', i
        print 'final selected:', selected
        break
    
